import { Service } from 'egg';
import { UserRole, UserStatus } from '../../model/user';

export default class AdminUserService extends Service {
    public async getUsers(role: UserRole, pageNum: number, pageSize: number) {
        const { service } = this;
        return await service.db.user.getUsersByPage(role, pageNum, pageSize);
    }

    public async getUsersCount(role: UserRole) {
        const { service } = this;
        const result = await service.db.user.getUsersCount(role);
        return result['count(*)'];
    }

    public async addUser(username: string, phone: string, role: UserRole,
                         password: string|undefined|null, adminId: number) {
        const { service } = this;
        const userId = await service.db.user.addUser(username, phone, role, password, adminId);
        return service.db.user.findOneById(userId);
    }

    public async updateUser(id: number,
        username: string|undefined,
        password: string|undefined,
        phone: string|undefined,
        role: UserRole|undefined,
        avatar: string|undefined,
        status: UserStatus|undefined,
        adminId: number|undefined) {
        const newUser: any = {};
        if (username) {
            newUser.username = username;
        }
        if (password) {
            if (this.ctx.user.role !== UserRole.SuperAdmin) {
                // 只有超级管理员才有修改用户密码的权限
                this.ctx.helper.invalidateRole('没有修改用户密码的权限怎');
            }
            newUser.password = password;
        }
        if (phone) {
            newUser.phone = phone;
        }
        if (role) {
            newUser.role = role;
        }
        if (avatar) {
            newUser.avatar = avatar;
        }
        if (status || status === 0) {
            newUser.status = status;
        }
        if (adminId) {
            newUser.admin_id = adminId; // 用户绑定的管理员默认为修改用户信息的管理员
        }
        await this.service.db.user.updateUser(id, newUser);
    }

    public async bindTeacher(studentId: number, teacherId: number, conn?: any) {
        if (!conn) {
            conn = this.app.mysql;
        }
        await conn.update('user', { teacher_id: teacherId }, { where: { id: studentId }});
    }
}
